import { PageConfig } from 'next';
import anylogger from 'anylogger';
import '@mmstudio/an000042';
import an48 from '@mmstudio/an000048';
import { tbclass, tbstudent } from '../../../../../atoms/db';

const logger = anylogger('pages/api/class/add/content/add.api');

export type Result = {
	ok: true;
} | {
	ok: false;
	message: string;
};

export type Message = {
	class_id: string;
	students: string[];
}

/**
 * pages/api/class/add/content/add.api
 */
const handler = an48<Result>();

handler.post(async (req, res) => {
	try {
		logger.debug('msg body:', req.body);
		const { class_id, students } = req.body as Message;
		if (!class_id || !students) {
			res.status(200).json({
				ok: false,
				message: '缺失参数'
			});
			return;
		}
		if (students.length > 0) {
			const cls = await tbclass()
				.first('*')
				.where({
					class_id
				});
			if (!cls) {
				res.status(200).json({ ok: false, message: '班级不存在' });
				return;
			}
			// if(student.classnumber)
			await tbstudent()
				.update({
					class_id,
					majorname: cls.majorname,
					grade: cls.grade,
					classname: cls.classname
				})
				.whereIn('student_id', students);
		}

		res.status(200).json({ ok: true });
	} catch (error) {
		logger.trace(error);
		res.status(200).json({ ok: false, message: (error as Error).message });
	}
});

export const config = {} as PageConfig;

export default handler;
